package k8s

import (
	"k8s-gpu-collector/pkg/config"
	"k8s-gpu-collector/pkg/utils/errOnce"

	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
)

var (
	defaultClientset *kubernetes.Clientset
	o                errOnce.ErrOnce
)

func init() {
	o = errOnce.NewErrOnce()
}

func GetDefaultClientset() *kubernetes.Clientset {
	err := o.Do(func() error {
		// init clientset
		globalConfig, err := config.InitGlobalConfig()
		if err != nil {
			return err
		}
		defaultClientset, _ = NewClientSet(globalConfig.InCluster, globalConfig.KubeconfigFile)
		return nil
	})
	if err != nil {
		panic(err)
	}
	return defaultClientset
}

func NewClientSet(inCluster bool, kubeconfigFile string) (*kubernetes.Clientset, error) {
	var config *rest.Config
	var err error
	if inCluster {
		config, err = rest.InClusterConfig()

	} else {
		config, err = clientcmd.BuildConfigFromFlags("", kubeconfigFile)
	}
	if err != nil {
		return nil, err
	}
	cs, err := kubernetes.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	return cs, nil
}
